import http from '@/utils/request'
import configService from './configService'
import store from 'store2'

const authService = {};
(function (service) {
  let loginCount = 0

  function getRequestUrl (url) {
    return configService.buildRequestUrl(url)
  }

  /**
   * 检测认证是否已开启
   */
  service.enable = function () {
    if (!window.config.VUE_AUTH_ENABLE) {
      return new Promise((resolve, reject) => {
        resolve(false)
      })
    }
    if (window.config.VUE_APP_DSG_ONLY) {
      return new Promise((resolve, reject) => {
        resolve(true)
      })
    }
    return http.get(getRequestUrl('/auth/enable'))
  }

  /**
   * 获取用于认证的Url
   */
  service.loginUrl = function () {
    return http.get(getRequestUrl('/auth/loginUrl') + '?publicUrl=' + window.config.VUE_APP_BASE_URL.substring(0, window.config.VUE_APP_BASE_URL.length - 1))
  }

  /**
   * 获取用于登出的Url
   */
  service.logoutUrl = function () {
    return new Promise((resolve, reject) => {
      const url = getRequestUrl('/auth/logout')
      resolve(url)
    })
  }

  service.logout2 = () => {
    service.logoutUrl().then(url => {
      http.get(url).then(res => {
      }, () => {
        location.href = window.config.VUE_APP_SSO_URL + '/logout?service=' + location.href
      })
    })
  }

  /**
   * 获取登录用户
   */
  service.loginUser = function () {
    const user = http.get(getRequestUrl('/auth/loginUser'))
    console.log('loginUser')
    return user
  }

  /**
   * 获取jwtToken
   */
  service.getJwtToken = function () {
    return http.get(getRequestUrl('/auth/getJwtToken'))
  }

  /**
   * 根据名称获取getJwtTokenByName(免登陆)
   */
  service.getJwtTokenByName = function (name) {
    return http.get(getRequestUrl('/auth/getJwtTokenByName?name=' + name))
  }

  /**
   * 检测登录密码
   */
  service.checkLoginPwd = function () {
    return http.get(getRequestUrl('/auth/checkLoginPwd'))
  }

  /**
   * 加载登录用户信息
   */
  function loadLoginUser () {
    return new Promise((resolve, reject) => {
      // eslint-disable-next-line no-undef
      const loggedin = dp.getQueryParam('loggedin')
      console.log('loggedin', loggedin)
      // 获取登录用户信息
      service.loginUser().then(d => {
        // 取得用户信息
        resolve(d)
        loginCount = 0
      }, e1 => {
        loginByJwt().then(d => {
          resolve(d)
          loginCount = 0
        }, e => {
          // 未取得用户信息
          loginCount++
          console.log('loginCount', loginCount)
          console.log('loggedin', loggedin)
          if (loginCount >= 3 || loggedin === '1') {
            // 登录失败超过5次或者已经登录
            // eslint-disable-next-line prefer-promise-reject-errors
            reject('登录失败！')
          } else {
            // 进行登录处理
            console.log('login1111')
            login(resolve, reject)
          }
        })
      })
    })
  }

  /**
   * 登录
   * @param {Function} resolve 登录成功
   * @param {Function} reject 登录失败
   */
  function login (resolve, reject) {
    // 获取登录地址
    service.loginUrl().then((d) => {
        let url = d
        url += url.indexOf('?') === -1 ? '?' : '&'
        url += '&redirect2=' + encodeURIComponent(location.href)
        store('3rd_redirect', { url: location.href })
        // 重定向到登录页面
        location.href = url
      },
      (e) => {
        reject(e)
      }
    )
  }

  /**
   * 通过iframe进行登录
   * @param {String} url 登录地址
   */
  function loginByIframe (url) {
    const promise = new Promise((resolve, reject) => {
      const iframe = document.createElement('iframe')
      iframe.style.cssText = 'height: 100%; width: 100%; position: fixed; top: 0; left: 0; z-index:99999999; border: none;'
      iframe.className = 'iframe-login3rd'
      iframe.src = url
      document.body.appendChild(iframe)
      const closeLogin = function closeLogin (m) {
        try {
          const data = JSON.parse(m.data)
          if (data.type === 'login3rd') {
            if (data.state === 'success') {
              window.removeEventListener('message', closeLogin)
              iframe.remove()
              resolve()
            } else {
              reject()
            }
          }
        } catch (e) {
          console.error(e)
        }
      }
      window.addEventListener('message', closeLogin)
    })
    return promise
  }

  /**
   * 通过Jwt登录
   * @returns
   */
  function loginByJwt () {
    return new Promise((resolve, reject) => {
      let autoLoginName = window.config.VUE_APP_AUTO_LOGIN_USER
      if (location.href.indexOf('userName') > -1) {
        autoLoginName = location.href.split('&')[1].split('=')[1]
      }
      console.log('autoLoginName', autoLoginName)
      if (autoLoginName) {
        service.getJwtTokenByName(autoLoginName).then(d => {
          const jwtToken = d
          // eslint-disable-next-line no-undef
          const daskToken = dp.getQueryParam('DASCTK')
          if (daskToken && http.addDefaultHeader) {
            http.addDefaultHeader({
              name: 'DASCTK',
              value: daskToken
            })
          }
          if (jwtToken && http.addDefaultHeader) {
            // 植入jwt标记
            http.addDefaultHeader({
              name: 'Authorization',
              value: 'JwtToken ' + jwtToken
            })
            // 获取登录用户信息
            service.loginUser().then(d => {
              // 取得用户信息
              resolve(d)
            }, e => {
              reject('登录失败！')
            })
          } else {
            reject('不满足jwt登录条件')
          }
        }, e => {
          reject('登录失败！')
        })
      } else {
        // eslint-disable-next-line no-undef
        const jwtToken = dp.getQueryParam('jwtToken')
        // eslint-disable-next-line no-undef
        const daskToken = dp.getQueryParam('DASCTK')
        if (daskToken && http.addDefaultHeader) {
          http.addDefaultHeader({
            name: 'DASCTK',
            value: daskToken
          })
        }
        if (window.config.VUE_APP_DSG_ONLY) {
          // 获取登录用户信息
          service.loginUser().then(d => {
            // 取得用户信息
            console.log('loginUser result', d)
            resolve(d)
          }, e => {
            reject('登录失败！')
          })
        } else {
          if (jwtToken && http.addDefaultHeader) {
            // 植入jwt标记
            http.addDefaultHeader({
              name: 'Authorization',
              value: 'JwtToken ' + jwtToken
            })
            // 获取登录用户信息
            service.loginUser().then(d => {
              // 取得用户信息
              resolve(d)
            }, e => {
              reject('登录失败！')
            })
          } else {
            reject('不满足jwt登录条件')
          }
        }
      }
    })
  }

  /**
   * 认证
   */
  service.auth = function () {
    return new Promise((resolve, reject) => {
      // 判断是否启用认证
      service.enable().then((d) => {
        if (d) {
          loadLoginUser().then(d => {
            resolve(d)
          }, e => {
            reject(e)
          })
        } else {
          // 未启用，则使用默认用户或者url地址中携带的用户进入系统
          resolve('')
        }
      })
    })
  }

  /**
   * 登出
   */
  service.logout = function () {
    var promise = new Promise((resolve, reject) => {
      service.logoutUrl().then(url => {
        const iframe = document.createElement('iframe')
        iframe.style.cssText = 'height: 100%; width: 100%; position: fixed; top: 0; left: 0; z-index:99999999; border: none; display: none;'
        iframe.className = 'iframe-logout3rd'
        iframe.onload = () => {
          setTimeout(() => {
            resolve()
          }, 30)
          iframe.remove()
        }
        iframe.src = url
        document.body.appendChild(iframe)
      })
    })
    return promise
  }
})(authService)

export default authService
